package com.sl.plugin.step.selenium.ai;

import cn.hutool.core.util.StrUtil;
import com.sl.core.engine.ai.AiPostBO;
import com.sl.core.engine.ai.AiSOLOFactory;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import lombok.SneakyThrows;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

/**
 */
public class SeleniumAIComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {

    public SeleniumAIComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }

    @SneakyThrows
    @Override
    public WebDriver input(WebDriver driver) {
        String modelCode = meta.getStrAttr("modelCode");
        String prompt = meta.getStrAttr("prompt");
        String operatorCode = meta.getStrAttr("operatorCode");
        String inputValue = meta.getStrAttr("inputValue");

        AiPostBO aiSOLOBO = new AiPostBO();
        aiSOLOBO.setAiCode(modelCode);
        aiSOLOBO.setKeywords(prompt);

        //先等待加载完毕
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));


        // 转换为 JavascriptExecutor 以执行脚本
        JavascriptExecutor js = (JavascriptExecutor) driver;


        // 执行JavaScript：克隆DOM → 移除所有script和style标签 → 返回处理后的HTML
        // 执行JavaScript：克隆DOM → 移除指定标签 → 返回处理后的HTML
        String pageHtml = (String) js.executeScript("""
                // 深克隆<html>根元素（不影响原始页面）
                const clone = document.documentElement.cloneNode(true);
                
                // 移除所有<script>标签
                clone.querySelectorAll('script').forEach(elem => elem.remove());
                
                // 移除所有<style>标签
                clone.querySelectorAll('style').forEach(elem => elem.remove());
                
                // 移除所有<link>标签（通常用于引入CSS、图标等）
                clone.querySelectorAll('link').forEach(elem => elem.remove());
                
                // 移除所有<svg>标签（矢量图形）
                clone.querySelectorAll('svg').forEach(elem => elem.remove());
                
                // 返回处理后的HTML
                return clone.outerHTML;
            """);

        // 如需包含 DOCTYPE 声明，可额外拼接（浏览器通常不会在 outerHTML 中返回 DOCTYPE）
        String doctype = (String) js.executeScript(
                "return new XMLSerializer().serializeToString(document.doctype);"
        );
        String fullHtml = doctype + "\n" + pageHtml; // 拼接 DOCTYPE 和 HTML 内容

        aiSOLOBO.setPrefixKeywords("下面是一个网页的html["+fullHtml+"],你需要根据提示只给出元素的selector ,下面是提示");

        String result = AiSOLOFactory.INSTANCE.execute(aiSOLOBO, null);
            logBasic("AI匹配到的元素是"+result);
            if(StrUtil.isBlank(result)){
                return driver;
            }
        // 再获取HTML
        if(StrUtil.equals(operatorCode,"input")){
            WebElement usernameInput = wait.until(
                    ExpectedConditions.presenceOfElementLocated(By.cssSelector(result))
            );

            // 输入用户名
            usernameInput.sendKeys(inputValue);
        }else if(StrUtil.equals(operatorCode,"enter")){
            driver.findElement(By.cssSelector(result)).sendKeys(Keys.ENTER);

        }
        return driver;
    }
}
